package com.hd.hdxgddcommon.utils;


import java.io.Serializable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * String工具
 * 主要对 StringUtils 的一些方法进行重写,达到更方便的使用
 *
 * @author zhou-baicheng
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {

    public static String buildSmsString(String title) {
        if (title != null && title.length() > 16)
            title = title.substring(0, 16);
        StringBuffer sb = new StringBuffer();
        sb.append("'").append(title).append("'");
        return sb.toString();
    }


    public static String valueOf(Object o) {
        return o == null ? "" : String.valueOf(o);
    }

    public static String buildLikeLeft(String text) {
        return "%" + text;
    }

    public static String buildLikeRight(String text) {
        return text + "%";
    }

    public static String buildLikeAll(String text) {
        return "%" + text + "%";
    }

    /**
     * 一次性判断多个或单个对象为空。
     *
     * @param objects
     * @return 只要有一个元素为Blank，则返回true
     * @author zhou-baicheng
     */
    public static boolean isBlank(Object... objects) {
        Boolean result = false;
        for (Object object : objects) {
            if (null == object || "".equals(object.toString().trim())
                    || "null".equals(object.toString().trim())) {
                result = true;
                break;
            }
        }
        return result;
    }

    public static String getRandomNums(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    public static String getRandom(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 取得大写字母还是小写字母
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                sb.append((char) (choice + random.nextInt(26)));
            } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
                sb.append(String.valueOf(random.nextInt(10)));
            }
        }
        return sb.toString();
    }

    /**
     * 一次性判断多个或单个对象不为空。
     *
     * @param objects
     * @return 只要有一个元素不为Blank，则返回true
     * @author zhou-baicheng
     */
    public static boolean isNotBlank(Object... objects) {
        return !isBlank(objects);
    }

    public static boolean isBlank(String... objects) {
        Object[] object = objects;
        return isBlank(object);
    }

    public static boolean isNotBlank(String... objects) {
        Object[] object = objects;
        return !isBlank(object);
    }

    public static boolean isBlank(String str) {
        Object object = str;
        return isBlank(object);
    }

    public static boolean isNotBlank(String str) {
        Object object = str;
        return !isBlank(object);
    }

    /**
     * 判断一个字符串在数组中存在几个
     *
     * @param baseStr
     * @param strings
     * @return
     */
    public static int indexOf(String baseStr, String[] strings) {

        if (null == baseStr || baseStr.length() == 0 || null == strings)
            return 0;

        int i = 0;
        for (String string : strings) {
            boolean result = baseStr.equals(string);
            i = result ? ++i : i;
        }
        return i;
    }

    public static String trimToEmpty(Object str) {
        return (isBlank(str) ? "" : str.toString().trim());
    }

    /**
     * 将 Strig  进行 BASE64 编码
     *
     * @param str [要编码的字符串]
     * @param bf  [true|false,true:去掉结尾补充的'=',false:不做处理]
     * @return
     */
//    public static String getBASE64(String str, boolean... bf) {
//        if (StringUtils.isBlank(str)) return null;
//        String base64 = new BASE64Encoder().encode(str.getBytes());
//        //去掉 '='
//        if (isBlank(bf) && bf[0]) {
//            base64 = base64.replaceAll("=", "");
//        }
//        return base64;
//    }

    /**
     * 将 BASE64 编码的字符串 s 进行解码
     **/
//    public static String getStrByBASE64(String s) {
//        if (isBlank(s)) return "";
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            byte[] b = decoder.decodeBuffer(s);
//            return new String(b);
//        } catch (Exception e) {
//            return "";
//        }
//    }

    /**
     * 把Map转换成get请求参数类型,如 {"name"=20,"age"=30} 转换后变成 name=20&age=30
     *
     * @param map
     * @return
     */
    public static String mapToGet(Map<? extends Object, ? extends Object> map) {
        String result = "";
        if (map == null || map.size() == 0) {
            return result;
        }
        Set<? extends Object> keys = map.keySet();
        for (Object key : keys) {
            result += ((String) key + "=" + (String) map.get(key) + "&");
        }

        return isBlank(result) ? result : result.substring(0, result.length() - 1);
    }

    /**
     * 把一串参数字符串,转换成Map 如"?a=3&b=4" 转换为Map{a=3,b=4}
     *
     * @param args
     * @return
     */
    public static Map<String, ? extends Object> getToMap(String args) {
        if (isBlank(args)) {
            return null;
        }
        args = args.trim();
        //如果是?开头,把?去掉
        if (args.startsWith("?")) {
            args = args.substring(1, args.length());
        }
        String[] argsArray = args.split("&");

        Map<String, Object> result = new HashMap<String, Object>();
        for (String ag : argsArray) {
            if (!isBlank(ag) && ag.indexOf("=") > 0) {

                String[] keyValue = ag.split("=");
                //如果value或者key值里包含 "="号,以第一个"="号为主 ,如  name=0=3  转换后,{"name":"0=3"}, 如果不满足需求,请勿修改,自行解决.

                String key = keyValue[0];
                String value = "";
                for (int i = 1; i < keyValue.length; i++) {
                    value += keyValue[i] + "=";
                }
                value = value.length() > 0 ? value.substring(0, value.length() - 1) : value;
                result.put(key, value);

            }
        }

        return result;
    }

    /**
     * 转换成Unicode
     *
     * @param str
     * @return
     */
    public static String toUnicode(String str) {
        String as[] = new String[str.length()];
        String s1 = "";
        for (int i = 0; i < str.length(); i++) {
            int v = str.charAt(i);
            if (v >= 19968 && v <= 171941) {
                as[i] = Integer.toHexString(str.charAt(i) & 0xffff);
                s1 = s1 + "\\u" + as[i];
            } else {
                s1 = s1 + str.charAt(i);
            }
        }
        return s1;
    }

    /**
     * 合并数据
     *
     * @param v
     * @return
     */
    public static String merge(Object... v) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < v.length; i++) {
            sb.append(v[i]);
        }
        return sb.toString();
    }

    /**
     * 判断字符串是否包含汉字
     *
     * @param txt
     * @return
     */
    public static Boolean containsCN(String txt) {
        if (isBlank(txt)) {
            return false;
        }
        for (int i = 0; i < txt.length(); i++) {

            String bb = txt.substring(i, i + 1);

            boolean cc = Pattern.matches("[\u4E00-\u9FA5]", bb);
            if (cc)
                return cc;
        }
        return false;
    }

    /**
     * 去掉HTML代码
     *
     * @param news
     * @return
     */
    public static String removeHtml(String news) {
        String s = news.replaceAll("amp;", "").replaceAll("<", "<").replaceAll(">", ">");

        Pattern pattern = Pattern.compile("<(span)?\\sstyle.*?style>|(span)?\\sstyle=.*?>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(s);
        String str = matcher.replaceAll("");

        Pattern pattern2 = Pattern.compile("(<[^>]+>)", Pattern.DOTALL);
        Matcher matcher2 = pattern2.matcher(str);
        String strhttp = matcher2.replaceAll(" ");


        String regEx = "(((http|https|ftp)(\\s)*((\\:)|：))(\\s)*(//|//)(\\s)*)?"
                + "([\\sa-zA-Z0-9(\\.|．)(\\s)*\\-]+((\\:)|(:)[\\sa-zA-Z0-9(\\.|．)&%\\$\\-]+)*@(\\s)*)?"
                + "("
                + "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])"
                + "(\\.|．)(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
                + "(\\.|．)(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
                + "(\\.|．)(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])"
                + "|([\\sa-zA-Z0-9\\-]+(\\.|．)(\\s)*)*[\\sa-zA-Z0-9\\-]+(\\.|．)(\\s)*[\\sa-zA-Z]*"
                + ")"
                + "((\\s)*(\\:)|(：)(\\s)*[0-9]+)?"
                + "(/(\\s)*[^/][\\sa-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$\\=~_\\-@]*)*";
        Pattern p1 = Pattern.compile(regEx, Pattern.DOTALL);
        Matcher matchhttp = p1.matcher(strhttp);
        String strnew = matchhttp.replaceAll("").replaceAll("(if[\\s]*\\(|else|elseif[\\s]*\\().*?;", " ");


        Pattern patterncomma = Pattern.compile("(&[^;]+;)", Pattern.DOTALL);
        Matcher matchercomma = patterncomma.matcher(strnew);
        String strout = matchercomma.replaceAll(" ");
        String answer = strout.replaceAll("[\\pP‘’“”]", " ")
                .replaceAll("\r", " ").replaceAll("\n", " ")
                .replaceAll("\\s", " ").replaceAll("　", "");


        return answer;
    }

    /**
     * 把数组的空数据去掉
     *
     * @param array
     * @return
     */
    public static List<String> array2Empty(String[] array) {
        List<String> list = new ArrayList<String>();
        for (String string : array) {
            if (StringUtils.isNotBlank(string)) {
                list.add(string);
            }
        }
        return list;
    }

    /**
     * 把数组转换成set
     *
     * @param array
     * @return
     */
    public static Set<?> array2Set(Object[] array) {
        Set<Object> set = new TreeSet<Object>();
        for (Object id : array) {
            if (null != id) {
                set.add(id);
            }
        }
        return set;
    }

    /**
     * serializable toString
     *
     * @param serializable
     * @return
     */
    public static String toString(Serializable serializable) {
        if (null == serializable) {
            return null;
        }
        try {
            return (String) serializable;
        } catch (Exception e) {
            return serializable.toString();
        }
    }

    public static List<String> substringTreeId(String treeId) {
        if (StringUtils.isBlank(treeId)) return Collections.emptyList();

        char[] array = "_".toCharArray();

        List<String> result = new ArrayList<>();

        if (treeId.contains("_")) {
            int l = treeId.length();
            int indexLength = 0;
            for (int i = 0; i < l; i++)
                if (array[0] == treeId.charAt(i))
                    indexLength++;
            for (int i = 1; i <= indexLength + 1; i++) {
                result.add(treeId.substring(0, 5 * i - 1));
            }
        } else
            result.add(treeId);
        return result;
    }


    /**
     * 去除右边的str
     *
     * @param source
     * @param str
     * @return
     */
    public static String rightTrimStr(String source, String str) {
        while (source.endsWith(str)) {
            source = source.substring(0, source.length() - str.length());
        }

        return source;
    }

    /**
     * 去除左边的str
     *
     * @param source
     * @param str
     * @return
     */
    public static String leftTrimStr(String source, String str) {
        while (source.startsWith(str)) {
            source = source.substring(str.length(), source.length());
        }

        return source;
    }

    /**
     * 右填充
     *
     * @param text
     * @param len
     * @param c
     * @return
     */
    public static String rightPadding(String text, int len, char c) {
        StringBuffer buffer = null;
        int curSize;
        if (text != null) {
            curSize = text.length();
            buffer = new StringBuffer(text);
        } else {
            curSize = 0;
            buffer = new StringBuffer();
        }

        while (curSize < len) {
            buffer.append(c);
            ++curSize;
        }

        return buffer.toString();
    }


    /**
     * 对象转string
     *
     * @param obj
     * @return
     */
    public static String objToString(Object obj) {
        return obj != null && !obj.toString().equalsIgnoreCase("null") ? obj.toString().trim() : "";
    }

    /**
     * 默认字符串
     *
     * @param obj
     * @param defaultStr
     * @return
     */
    public static String objToStringWithDefault(Object obj, String defaultStr) {
        String ret = objToString(obj);
        return ret.length() < 1 ? defaultStr : ret;
    }

    public static List<Integer> stringArrayToInt(String[] s) {
        Integer[] intTemp = new Integer[s.length];
        for (int i = 0; i < s.length; i++) {
            try {
                intTemp[i] = Integer.parseInt(s[i]);
            } catch (Exception e) {
                intTemp[i] = 0;
            }
        }
        return Arrays.asList(intTemp);
    }


    public static String encrypt(String str) {
        String m2 = MathUtil.encode64(MathUtil.DEFAULT_SECRET_KEY2, str);
        return m2;
    }

    public static String decrypt(String str) {
        String n = MathUtil.decode64(MathUtil.DEFAULT_SECRET_KEY2, str);
        return n;
    }


    // 生成digCount位随机数字
    public static String generateRandomCode(int digCount) {

        Random rnd = new Random();

        StringBuilder sb = new StringBuilder(digCount);

        for (int i = 0; i < digCount; i++)
            sb.append((char) ('0' + rnd.nextInt(10)));

        return sb.toString();
    }
}
